package com.chorye.function.schedule.config;

import com.chorye.function.schedule.component.QuartzJobFactory;
import org.quartz.spi.JobFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Properties;

/**
 * 定时任务配置类
 *
 * @author Chorye
 */
@Configuration
public class QuartzConfig {

    /**
     * quartz配置文件所在路径
     */
    private static final String QUARTZ_PROPERTIES_PATH = "config/quartz.properties";
    /**
     * 日志工具
     */
    private final Logger log = LoggerFactory.getLogger(QuartzConfig.class);

    /**
     * 创建任务工厂
     *
     * @param applicationContext spring应用上下文
     * @return 任务工厂
     */
    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        // 创建自动注入的任务工厂
        QuartzJobFactory jobFactory = new QuartzJobFactory();
        // 设置上下文
        jobFactory.setApplicationContext(applicationContext);
        // 返回
        return jobFactory;
    }

    /**
     * 创建任务调度器工厂
     *
     * @param jobFactory 任务工厂
     * @return 任务调度器工厂
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) {
        // 创建任务调度器工厂
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        // 设置任务工厂
        schedulerFactoryBean.setJobFactory(jobFactory);
        // 设置延迟启动的时长
        schedulerFactoryBean.setStartupDelay(20);
        // 用于quartz集群,加载quartz数据源配置
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        // 返回
        return schedulerFactoryBean;
    }

    /**
     * 封装处理quartz的配置信息
     *
     * @return quartz的配置信息
     */
    private Properties quartzProperties() {
        // 创建属性工厂
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        // 设置配置文件信息
        factoryBean.setLocation(new ClassPathResource(QUARTZ_PROPERTIES_PATH));
        try {
            // 属性工程读取属性
            factoryBean.afterPropertiesSet();
            // 返回属性对象
            return factoryBean.getObject();
        } catch (Exception e) {
            // 打印错误
            if (log.isErrorEnabled()) {
                log.error(e.toString());
            }
            return null;
        }
    }
}